package com.chatgpt.api.service.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes({JSONArray.class})
public class JsonArrayTypeHandler extends BaseTypeHandler<JSONArray> {
  @Override
  public void setNonNullParameter(
      PreparedStatement preparedStatement, int i, JSONArray objects, JdbcType jdbcType)
      throws SQLException {
    preparedStatement.setString(i, JSON.toJSONString(objects));
  }

  @Override
  public JSONArray getNullableResult(ResultSet resultSet, String s) throws SQLException {
    String str = resultSet.getString(s);
    return JSON.parseArray(str);
  }

  @Override
  public JSONArray getNullableResult(ResultSet resultSet, int i) throws SQLException {
    String str = resultSet.getString(i);
    return JSON.parseArray(str);
  }

  @Override
  public JSONArray getNullableResult(CallableStatement callableStatement, int i)
      throws SQLException {
    String str = callableStatement.getString(i);
    return JSON.parseArray(str);
  }
}
